//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved

#include "pch.h"


using namespace Microsoft::WRL;

RenderObject::RenderObject():uid(0)
{

}


Sprite::Sprite():m_zOffset(0.f)
				,m_rotation(0.f)
				,m_needUpdateConstantBuffer(true)
{
	CD3D11_BUFFER_DESC constantBufferDescription(sizeof(SpriteConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
	DX::ThrowIfFailed(
		DirectX2DRender::Instance()->GetDevice()->CreateBuffer(
		&constantBufferDescription,
		nullptr,             
		&m_constantBufferSprite
		)
		);
}

bool Sprite::PreRender(uint layer, float zoffset)
{
	if(layer > RenderObjectManager::RenderObjectLayerNum)
		return false;

	RenderObjectManager::Instance()->AddSpriteToRenderList(this, (RenderObjectManager::RenderObjectLayer)layer);

	return true;
}

void Sprite::Render(Microsoft::WRL::ComPtr<ID3D11DeviceContext1> context)
{
	if(m_needUpdateConstantBuffer)
	{
		m_constantBufferSpriteData.world = scale(m_scale.x, m_scale.y, 0);
		m_constantBufferSpriteData.world = mul(rotationZRad(m_rotation), m_constantBufferSpriteData.world);
		m_constantBufferSpriteData.world = mul(translation(m_position.x, m_position.y, m_zOffset), m_constantBufferSpriteData.world);

		context->UpdateSubresource(
			m_constantBufferSprite.Get(),
			0,
			nullptr,
			&m_constantBufferSpriteData,
			0,
			0
			);

		m_needUpdateConstantBuffer = false;
	}


	context->VSSetConstantBuffers(
		1,                              
		1,                              
		m_constantBufferSprite.GetAddressOf()
		);

	context->PSSetShaderResources(
		0,                          
		1,                          
		m_TextureView.GetAddressOf()
		);
	context->DrawIndexed(NUMINDICES, 0, 0);
}

void Sprite::Update(float frame_time)
{
	
}

void Sprite::SetPosition(const float2& position)
{
	m_position= position;
	m_needUpdateConstantBuffer = true;	
}

void Sprite::SetPosition(const b2Vec2& position)
{
	m_position= float2(position.x, position.y);
	m_needUpdateConstantBuffer = true;
}

void Sprite::SetTransform(const float2& position, float rotation)
{
	m_position = position;
	m_rotation = rotation;
	m_needUpdateConstantBuffer = true;
}

void Sprite::SetScale(const float2& scale)
{
	m_scale = scale;
	m_needUpdateConstantBuffer = true;
}

void Sprite::SetRotation(float rotation)
{
	m_rotation = rotation;
	m_needUpdateConstantBuffer = true;
}

void Sprite::SetUV(const float2& uv)
{
	m_uv = uv;
	m_needUpdateConstantBuffer = true;
}

void Sprite::SetTexture(Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> view)
{
	m_TextureView = view;
}